/*###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.9
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############*/

AntzBSWidgetBorder = function(){};
AntzBSWidgetBorder.prototype.toDom = function(widget, property, element){
	var container = document.createElement('div');
	var heading = document.createElement('h4');
	$(heading).text(widget.name);




	var enable = document.createElement('input');
	enable.type = 'checkbox';
	enable.checked = (widget.enabled);
	$(enable).attr('xml:widget_instance_id', widget.instanceId);
	$(enable).attr('xml:property_instance_id', property.instanceId);

	$(enable).click(function(){
		var widget = AntzBSHandler.findWidget($(this).attr('xml:widget_instance_id'));
		widget.enabled = this.checked*1;
		AntzBSHandler.saveWidgetProperty(widget.instanceId, 'enabled', this.checked*1);
	});


	container.appendChild(enable);


	$(container).append(heading);
	$(container).addClass(property.id);

	var control = document.createElement('div');

	var widgets = document.createElement('div');
	widgets.id = widget.instanceId+'_controls';
	widgets.className = widget.instanceId+'-widget-controls';
	$(widgets).addClass('controls');

	

	var sideNames = ['Top', 'Right', 'Bottom', 'Left'];
	var sides = ['top', 'right', 'bottom', 'left'];
	for(var i=0; i<sides.length; i++){
		var a = document.createElement('div');
		if(i==0){
			$(a).css('clear', 'left');
		}
		$(a).addClass('button');
		$(a).html(sideNames[i]);
		control.appendChild(a);
		$(a).attr('xml:widgetInstanceId', widget.instanceId);
		$(a).attr('xml:widgetSide', sides[i]);
		$(a).click(function(){
			AntzBSWidgetBorder.displayControls($(this).attr('xml:widgetSide'), $(this).attr('xml:widgetInstanceId'));
		});
		
	}

	control.appendChild(widgets);

	container.appendChild(control);
	return container;
}

AntzBSWidgetBorder.displayControls = function(side, widgetId){
	var widget = AntzBSHandler.findWidget(widgetId);
	widget.currentBorderSide = side;

	AntzBSHandler.saveWidgetProperty(widget.instanceId, 'currentBorderSide', side);
	var property = AntzBSHandler.findProperty(widget.propertyInstanceId);
	var element = AntzBSHandler.findElement(property.elementId);
	var controlDom = $('#'+widget.instanceId+'_controls').get(0);
	$(controlDom).html('');
	$('.button', controlDom.parentNode).each(function(){
		$(this).removeClass('selected');
		if($(this).attr('xml:widgetSide')==side){
			$(this).addClass('selected');
		}
	});

	var widgetDom = document.createElement('div');
	controlDom.appendChild(widgetDom);

	var heading = this.getHeading('Border Thickness');
	$(heading).attr('xml:widget_instance_id', widget.instanceId+'-thickness-'+side);
	$(widgetDom).append(heading);


	var value = document.createElement('input');
	value.type = 'text';
	eval('value.value = widget.'+side+'Thickness');
	$(value).attr('xml:widget_instance_id', widget.instanceId);


	$(value).keyup(function(){
		var widgetData = AntzBSHandler.findWidget($(this).attr('xml:widget_instance_id'));

		/*
		 * this will set properties widget.leftValue, widget.rightValue, widget.topValue, widget.bottomValue
		 */


		eval('widgetData.'+widgetData.currentBorderSide+'Thickness = "'+$(this).val()+'";');

		var selector = AntzBSHandler.getSelector(element);
		var thickness, unit;

		eval('thickness = widgetData.'+widgetData.currentBorderSide+'Thickness;');
		eval('unit = widgetData.'+widgetData.currentBorderSide+'Unit;');

		$(selector).css(property.cssName, thickness+''+unit);

		AntzBSHandler.saveWidgetProperty(widgetData.instanceId, widgetData.currentBorderSide+'Thickness', thickness);
	});

	var options = {
		animate : true,
		max : widget.max,
		min : widget.min,
		orientation : widget.orientation,
		step : widget.step,
		value : value.value,
		slide : function(event, ui){
			value.value = ui.value;


		},
		stop : function(event, ui){

			eval('widget.'+widget.currentBorderSide+'Thickness = "'+ui.value+'";');

			var selector = AntzBSHandler.getSelector(element);
			var thickness, unit;

			eval('thickness = widget.'+widget.currentBorderSide+'Thickness;');
			eval('unit = widget.'+widget.currentBorderSide+'Unit;');

			$(selector).css(property.cssName, thickness+''+unit);

			AntzBSHandler.saveWidgetProperty(widget.instanceId, widget.currentBorderSide+'Thickness', thickness);
			AntzBSHandler.refreshCssOutput();


		}

	}

	var slider = document.createElement('div');

	widgetDom.appendChild(slider);

	$(slider).slider(options);

	widgetDom.appendChild(value);






	var heading = this.getHeading('Border Colour');
	$(heading).attr('xml:widget_instance_id', widget.instanceId+'-color-'+side);
	$(widgetDom).append(heading);

	var picker = document.createElement('div');
	var colorValue;

	eval('colorValue = widget.'+side+'Color;');

	var colorOpts = {
		flat : true,
		color: colorValue,
		onSubmit : function(hsb, hex, rgb){
			eval('widget.'+side+'Color = "#"+hex');
			var selector = AntzBSHandler.getSelector(element);

			$(selector).css(widget.cssName, '#'+hex);
			AntzBSHandler.saveWidgetProperty(widget.instanceId, side+'Color', '#'+hex);
		}
	}
	$(picker).ColorPicker(colorOpts);
	widgetDom.appendChild(picker);










	var heading = this.getHeading('Border Style');
	$(heading).attr('xml:widget_instance_id', widget.instanceId+'-style-'+side);
	$(widgetDom).append(heading);

	var multi = document.createElement('select');
	$(multi).attr('xml:side', side);
	$(multi).attr('xml:widget_instance_id', widget.instanceId);
	var selectedStyle = null;
	eval('selectedStyle = widget.'+side+'Style;');

	for(var i=0; i<widget.styles.length; i++){
		var styleName = widget.styleNames[i];
		var styleValue = widget.styles[i];
		var option = new Option(styleName, styleValue, (selectedStyle==styleValue), (selectedStyle==styleValue));
		multi.options[multi.options.length] = option;

	}

	$(multi).change(function(){
		var side, widgetInstanceId;
		side = $(this).attr('xml:side');
		widgetInstanceId = $(this).attr('xml:widget_instance_id');
		var widget = AntzBSHandler.findWidget(widgetInstanceId);
		var newValue;
		newValue = this.options[this.selectedIndex].value;
		AntzBSHandler.saveWidgetProperty(widgetInstanceId, side+'Style', newValue);
	});

	widgetDom.appendChild(multi);





	return widgetDom;
}
AntzBSWidgetBorder.getEnable = function(widget, side){
	
}
AntzBSWidgetBorder.getHeading = function(headingText){
	var heading = document.createElement('h5');
	$(heading).text(headingText);
	return heading;
}





AntzBSWidgetBorderCorner = function(){};
AntzBSWidgetBorderCorner.prototype.toDom = function(widget, property, element){
	var container = document.createElement('div');
	var heading = document.createElement('h4');
	$(heading).html(widget.name);
	$(container).append(heading);

	var heading = document.createElement('h5');
	$(heading).text('Top-Left');
	container.appendChild(heading);
	container.appendChild(AntzBSWidgetBorderCorner.getSlider(widget, 'topleftValue1'));
	container.appendChild(AntzBSWidgetBorderCorner.getSlider(widget, 'topleftValue2'));



	var heading = document.createElement('h5');
	$(heading).text('Top-Right');
	container.appendChild(heading);
	container.appendChild(AntzBSWidgetBorderCorner.getSlider(widget, 'toprightValue1'));
	container.appendChild(AntzBSWidgetBorderCorner.getSlider(widget, 'toprightValue2'));
	


	var heading = document.createElement('h5');
	$(heading).text('Bottom-Right');
	container.appendChild(heading);
	container.appendChild(AntzBSWidgetBorderCorner.getSlider(widget, 'bottomrightValue1'));
	container.appendChild(AntzBSWidgetBorderCorner.getSlider(widget, 'bottomrightValue2'));



	var heading = document.createElement('h5');
	$(heading).text('Bottom Left');
	container.appendChild(heading);
	container.appendChild(AntzBSWidgetBorderCorner.getSlider(widget, 'bottomleftValue1'));
	container.appendChild(AntzBSWidgetBorderCorner.getSlider(widget, 'bottomleftValue2'));



	return container;
}

AntzBSWidgetBorderCorner.getSlider = function(widget, varname){
	var container = document.createElement('div');

	var value = document.createElement('input');
	value.type = 'text';
	eval('value.value = widget.'+varname);
	$(value).attr('xml:widget_instance_id', widget.instanceId);
	$(value).attr('xml:widget_property_name', varname);


	$(value).keyup(function(){
		var widgetData = AntzBSHandler.findWidget($(this).attr('xml:widget_instance_id'));
		var varname = $(this).attr('xml:widget_property_name');

		/*
		 * this will set properties widget.leftValue, widget.rightValue, widget.topValue, widget.bottomValue
		 */


		eval('widgetData.'+varname+' = "'+$(this).val()+'";');

		AntzBSHandler.saveWidgetProperty(widgetData.instanceId, widgetData.currentBorderSide+'Thickness', $(this).val());
	});

	var val;
	eval('val = widget.'+varname);

	var options = {
		animate : true,
		max : widget.max,
		min : widget.min,
		orientation : widget.orientation,
		step : widget.step,
		value : val,
		slide : function(event, ui){
			value.value = ui.value;
		},
		stop : function(event, ui){
			eval('widget.'+varname+' = "'+ui.value+'";');
			AntzBSHandler.saveWidgetProperty(widget.instanceId, varname, ui.value);
			AntzBSHandler.refreshCssOutput();
		}

	}

	var slider = document.createElement('div');

	container.appendChild(slider);

	$(slider).slider(options);

	container.appendChild(value);

	return container;
}

























AntzBSWidgetMulti = function(){};
AntzBSWidgetMulti.prototype.toDom = function(widget, property, element){
    var container = document.createElement('div');
    var heading = document.createElement('h4');
    $(heading).html(widget.name);
	$(heading).attr('xml:widget_instance_id', widget.instanceId);


	$(heading).click(function(){

		var widget = AntzBSHandler.findWidget($(this).attr('xml:widget_instance_id'));

		if(widget.open>0){
			// close it
			widget.open = 0;
			$(control).slideUp();
		}else{
			// open it
			widget.open = 1;
			$(control).slideDown();
		}
		AntzBSHandler.saveWidgetProperty(widget.instanceId, 'open', widget.open);

	});




	var enable = document.createElement('input');
	enable.type = 'checkbox';
	enable.checked = (widget.enabled);
	$(enable).attr('xml:widget_instance_id', widget.instanceId);
	$(enable).attr('xml:property_instance_id', property.instanceId);

	$(enable).click(function(){
		var widget = AntzBSHandler.findWidget($(this).attr('xml:widget_instance_id'));
		widget.enabled = this.checked*1;
		AntzBSHandler.saveWidgetProperty(widget.instanceId, 'enabled', this.checked*1);
	});

	container.appendChild(enable);
	container.appendChild(heading);
	
	
	var control = document.createElement('div');
	$(control).addClass('jfx-blockstyle-control');


	var select = document.createElement('select');
	$(select).attr('multiple', widget.multiple);
	$(select).attr('xml:widget_instance_id', widget.instanceId);

	for(var i=0; i<widget.options.length; i++){
		var selected = false;
		if(AntzBSWidgetMulti.hasValue(widget, widget.options[i].value)){
			selected = true;
		}
		var option = new Option(widget.options[i].name, widget.options[i].value, selected, selected);
		$(select).append(option);
	}

	$(select).change(function(){
		var value = this.options[this.selectedIndex].value;
		var widget = AntzBSHandler.findWidget($(this).attr('xml:widget_instance_id'));
		if(widget.multiple){
			if(AntzBSWidgetMulti.hasValue(widget, value)){
				// not changed
				alert('the value is the same: '+value);
			}else{
				widget.values[widget.values.length] = value;
			}

		}else{
			widget.values[0] = value;
		}
		AntzBSHandler.save();
	});

	control.appendChild(select);

	if(widget.open<=0){
		$(control).css('display', 'none');
	}


	container.appendChild(control);

    return container;
}

AntzBSWidgetMulti.hasValue = function(widget, value){
	for(var i=0; i<widget.values.length; i++){
		if(widget.values[i] == value){
			return true;
		}
	}
	return false;
}





/**
 * Slider widget
 */
var AntzBSWidgetSlider = function(){};
AntzBSWidgetSlider.prototype.toDom = function(widget, property, element){
	var container = document.createElement('div');

	var heading = document.createElement('h4');
	$(heading).text(widget.name);

	$(heading).attr('xml:widget_instance_id', widget.instanceId);

	var control = document.createElement('div');
	$(control).addClass('jfx-blockstyle-control');


	var enable = document.createElement('input');
	enable.type = 'checkbox';
	enable.checked = (widget.enabled);
	$(enable).attr('xml:widget_instance_id', widget.instanceId);
	$(enable).attr('xml:property_instance_id', property.instanceId);



	container.appendChild(enable);
	container.appendChild(heading);

	$(heading).click(function(){

		var widget = AntzBSHandler.findWidget($(this).attr('xml:widget_instance_id'));

		if(widget.open){
			// close it
			widget.open = 0;
			$(control).slideUp();
		}else{
			// open it
			widget.open = 1;
			$(control).slideDown();
		}
		AntzBSHandler.saveWidgetProperty(widget.instanceId, 'open', widget.open);
		
	});

	var value = document.createElement('input');
	value.type = 'text';
	value.value = widget.value;
	value.disabled = !widget.enabled;
	$(value).attr('xml:widget_instance_id', widget.instanceId);
	

	$(value).keyup(function(){
		var widgetData = AntzBSHandler.findWidget($(this).attr('xml:widget_instance_id'));
		widgetData.value = $(this).val();

		var selector = AntzBSHandler.getSelector(element);

		$(selector).css(property.cssName, widget.value+''+widget.unit);

		AntzBSHandler.saveWidgetProperty(widget.instanceId, 'value', widget.value);
	});

	var options = {
		disabled : !widget.enabled,
		animate : true,
		max : widget.max,
		min : widget.min,
		orientation : widget.orientation,
		step : widget.step,
		value : widget.value,
		slide : function(event, ui){
			value.value = ui.value;
			
			
		},
		stop : function(event, ui){
			
			widget.value = ui.value;

			var selector = AntzBSHandler.getSelector(element);
			
			$(selector).css(property.cssName, widget.value+''+widget.unit);

			AntzBSHandler.saveWidgetProperty(widget.instanceId, 'value', widget.value);
			AntzBSHandler.refreshCssOutput();


		}

	}

	var slider = document.createElement('div');
	
	control.appendChild(slider);

	$(slider).slider(options);

	control.appendChild(value);

	$(enable).click(function(){
		$(slider).slider('option', 'disabled', !this.checked);
		value.disabled = !this.checked;
		$('select', container).attr('disabled', !this.checked);
		var widget = AntzBSHandler.findWidget($(this).attr('xml:widget_instance_id'));
		widget.enabled = this.checked*1;
		AntzBSHandler.saveWidgetProperty(widget.instanceId, 'enabled', this.checked*1);
	});

	if(widget.showUnits){
		var units = document.createElement('select');
		$(units).attr('xml:widget_instance_id', widget.instanceId);
		units.disabled = !widget.enabled;
		
		for(var i=0; i<widget.units.length; i++){
			var selected = false;
			if(widget.units[i]==widget.unit){
				selected = true;
			}
			var li = new Option(widget.unitNames[i], widget.units[i], selected, selected);
			units.appendChild(li);

		}
		$(units).change(function(){
			var unit = this.options[this.selectedIndex].value;
			var widget = AntzBSHandler.findWidget($(this).attr('xml:widget_instance_id'));
			widget.unit = unit;
                        AntzBSHandler.saveWidgetProperty(widget.instanceId, 'unit', unit);
		});

		control.appendChild(units);
	}
	
	
	container.appendChild(control);

	if(widget.open<=0){
		$(control).css('display', 'none');
	}
	

	return container;
}






/**
 * File widget
 */
var AntzBSWidgetImage = function(){
};
AntzBSWidgetImage.prototype.toDom = function(widget, property, element){
	var container = document.createElement('div');

        var heading = document.createElement('h4');
        $(heading).html(widget.name);
        $(heading).attr('xml:widget_instance_id', widget.instanceId);

        var control = document.createElement('div');
        this.controlNode = control;
		$(control).addClass('jfx-blockstyle-control');
		$(control).addClass(widget.cssName);

        $(heading).click(function(){

		var widget = AntzBSHandler.findWidget($(this).attr('xml:widget_instance_id'));
		var control = $('.jfx-blockstyle-control', this.parentNode).get(0);

		if(widget.open){
			// close it
			widget.open = 0;
			$(control).slideUp();
		}else{
			// open it
			widget.open = 1;
			$(control).slideDown();
		}
		AntzBSHandler.saveWidgetProperty(widget.instanceId, 'open', widget.open);

	});

	var enable = document.createElement('input');
	enable.type = 'checkbox';
	enable.checked = widget.enabled;
	$(enable).attr('xml:widget_instance_id', widget.instanceId);
	$(enable).attr('xml:property_instance_id', property.instanceId);
	container.appendChild(enable);

	container.appendChild(heading);


	var preview = document.createElement('div');

	control.appendChild(preview);
	

	var treeview = document.createElement('ul');
	$(treeview).html(widget.filepicker);

	control.appendChild(treeview);
	
	control.cssName = 'JFX_Module_Blockstyle_Widget_File';

	$(treeview).treeview({
		persist: "location",
		collapsed: true,
		unique: true
	});


        //widget.previewNode = preview;
        preview.className = 'JFX_Module_Blockstyle_File_Preview';

		var filename = document.createElement('h5');
		$(filename).html(widget.path+'/'+widget.filename);
		filename.id = 'JFX_Module_Blockstyle_File_Preview_Filename';
		$(filename).addClass('jfx-toolbar-header');
		preview.appendChild(filename);

        var previewImage = document.createElement('img');
		previewImage.src = widget.url;
		previewImage.id = 'JFX_Module_Blockstyle_Previewimage';
        //widget.previewImageNode = previewImage;
        preview.appendChild(previewImage);
        
        
	
    $(enable).click(function(){
		var widget = AntzBSHandler.findWidget($(this).attr('xml:widget_instance_id'));
		widget.enabled = this.checked*1;
		AntzBSHandler.saveWidgetProperty(widget.instanceId, 'enabled', this.checked*1);
	});

	var apply = document.createElement('div');
	apply.className = 'apply';
	$(apply).html('Apply');
	$(apply).attr('xml:widget_instance_id', widget.instanceId);
	$(apply).click(function(){
		var widget = AntzBSHandler.findWidget($(this).attr('xml:widget_instance_id'));
		widget.path = widget.tempPath;
		widget.filename = widget.tempFilename;
		widget.tempFilename = '';
		widget.tempPath = '';
		AntzBSHandler.save();
	});

	var cancel = document.createElement('div');
	cancel.className = 'cancel';
	$(cancel).html('Cancel');
	$(cancel).attr('xml:widget_instance_id', widget.instanceId);
	$(cancel).click(function(){
		var widget = AntzBSHandler.findWidget($(this).attr('xml:widget_instance_id'));
		widget.tempPath = '';
		widget.tempFilename = '';
		widget.tempUrl = '';
		$('#'+widget.previewImageNodeId).attr('src', widget.url);
		widget.tempFilename = '';
		$('#JFX_Module_Blockstyle_File_Preview_Filename').html(widget.path+'/'+widget.filename);
	});

	preview.appendChild(cancel);
	preview.appendChild(apply);


	if(widget.open<=0){
		$(control).css('display', 'none');
	}


	container.appendChild(control);

	return container;
}


AntzBSWidgetImage.selectFile = function(url, widgetInstanceId, path, filename){
    // display the file preview
    var widget = AntzBSHandler.findWidget(widgetInstanceId);
	widget.tempPath = path;
	widget.tempFilename = filename;
	widget.tempUrl = url;
    $('#'+widget.previewImageNodeId).attr('src', url);
	$('#JFX_Module_Blockstyle_File_Preview_Filename').html(widget.tempPath+'/'+widget.tempFilename);
}

AntzBSWidgetImage.selectFolder = function(){
    // show the upload form

	



}





/**
 * Colour widget
 */
var AntzBSWidgetColor = function(){};
AntzBSWidgetColor.prototype.toDom = function(widget, property, element){
	var container = document.createElement('div');
	var control = document.createElement('div');
	$(control).addClass('jfx-blockstyle-control');

	$(control).addClass(widget.cssName);
	
	var heading = document.createElement('h4');
	$(heading).text(widget.name);
	$(heading).attr('xml:widget_instance_id', widget.instanceId);

	$(heading).click(function(){
		var widget = AntzBSHandler.findWidget($(this).attr('xml:widget_instance_id'));
		if(widget.open){
			$(control).slideUp();
			widget.open = 0;
		}else{
			$(control).slideDown();
			widget.open = 1;
		}
		AntzBSHandler.saveWidgetProperty(widget.instanceId, 'open', widget.open);
	});

	var enable = document.createElement('input');
	enable.type = 'checkbox';
	enable.checked = widget.enabled;
	$(enable).attr('xml:widget_instance_id', widget.instanceId);
	$(enable).attr('xml:property_instance_id', property.instanceId);


	container.appendChild(enable);

	container.appendChild(heading);

	var picker = document.createElement('div');

	var colorOpts = {
		flat : true,
		color: widget.value,//.replace('#', ''),
		onSubmit : function(hsb, hex, rgb){
			widget.value = hex;
			var selector = AntzBSHandler.getSelector(element);
			
			$(selector).css(widget.cssName, '#'+hex);
			AntzBSHandler.saveWidgetProperty(widget.instanceId, 'value', widget.value);
		}
	}
	$(picker).ColorPicker(colorOpts);
	control.appendChild(picker);

	
	
	$(enable).click(function(){
		var widgetData = AntzBSHandler.findWidget($(this).attr('xml:widget_instance_id'));
		widgetData.enabled = this.checked*1;
		$('.jfx-blockstyle-colorpicker', this.parentNode).attr('disabled', true);
		AntzBSHandler.saveWidgetProperty(widgetData.instanceId, 'enabled', this.checked*1);
	});

	container.appendChild(control);

	if(widget.open<=0){
		$(control).css('display', 'none');
	}



	return container;
}






var AntzBSWidget = function(){
	this.widgets = Array();
}

AntzBSWidget.toDom = function(property, element){
	var propertyDom = document.createElement('div');
	propertyDom.className = 'property';

	var heading = document.createElement('h3');
	$(heading).html(property.title);
	$(heading).attr('xml:property_instance_id', property.instanceId);
	propertyDom.appendChild(heading);

	var widgetDom = document.createElement('div');
	widgetDom.className = 'property-widgets';
	if(property.open<=0){
		$(widgetDom).css('display', 'none');
	}

	var widget;

	for(var i=0; i<property.widgets.length; i++){
		switch(property.widgets[i].id){
			case 'image':
				widget = new AntzBSWidgetImage();
			break;
			case 'color':
				widget = new AntzBSWidgetColor();
			break;
			case 'slider':
				widget = new AntzBSWidgetSlider();
			break;
			case 'multi':
				widget = new AntzBSWidgetMulti();
			break;
			case 'border':
				widget = new AntzBSWidgetBorder();
			break;
			case 'bordercorner':
				widget = new AntzBSWidgetBorderCorner();
			break;
			default:
				alert('cant find an action for widget '+property.widgets[i].id);
			break;
		}
		widgetDom.appendChild(widget.toDom(property.widgets[i], property, element));
	}

	$(heading).click(function(){
		var propertyInstanceId = $(this).attr('xml:property_instance_id');
		var property = AntzBSHandler.findProperty(propertyInstanceId);
		if(property.open>=1){
			// close it
			$('.property-widgets', this.parentNode).slideUp();
			AntzBSHandler.savePropertyProperty(propertyInstanceId, 'open', 0);
		}else{
			// open it
			$('.property-widgets', this.parentNode).slideDown();
			AntzBSHandler.savePropertyProperty(propertyInstanceId, 'open', 1);
		}
	});

	propertyDom.appendChild(widgetDom);
	return propertyDom;
}


AntzBSWidget.save = function(){
	AntzBSHandler.saveWidget(this);
}


/**
 * requires following keys to be set in object:
 * controlNode (html dom node)
 * previewNode (htmo dom node)
 * ajaxUrl (string url to ajax file)
 */
var AntzBSHandler = function(){
	this.controls = Array();
}


AntzBSHandler.displayTemplate = function(select){
	var value = select.options[select.selectedIndex].value;
	$.get(this.config.ajaxUrl, {'ajaxCommand':'set_template', 'template_id':value});
	this.save();
}



AntzBSHandler.togglePreviewState = function(){
	window.previewWindow = window.open(this.config.previewUrl.replace('&amp;', '&'), 'Preview Window', 'status=1, height=600, width=800, resizable=1');
	AntzBSHandler.saveHandlerProperty('previewNodeState', 'open');		
}


AntzBSHandler.toggleCssOutputState = function(){
	if($(this.outputNode).attr('xml:state')=='open'){
		// close it
		$(this.outputNode).fadeOut('slow');
		$(this.outputNode).attr('xml:state', 'closed');
		setTimeout(function(){
                    AntzBSHandler.saveHandlerProperty('outputNodePositionTop', AntzBSHandler.config.outputNodeDefaultPositionTop);
                    AntzBSHandler.saveHandlerProperty('outputNodePositionLeft', AntzBSHandler.config.outputNodeDefaultPositionLeft);
                }, 1000);

		this.saveHandlerProperty('outputNodeState', 'closed');
		
	}else{
		// open it
		$(this.outputNode).fadeIn();
		$(this.outputNode).attr('xml:state', 'open');
		this.outputNode.style.top = this.config.outputNodePositionTop;
		this.outputNode.style.left = this.config.outputNodePositionLeft;


		this.saveHandlerProperty('outputNodeState', 'open');

	}
}

AntzBSHandler.saveHandlerProperty = function(name, value){

	var ajaxConfig = {
		ajaxCommand : 'save_handler_property',
		name : name,
		value : value
	}
	$.get(this.config.ajaxUrl, ajaxConfig, function(){AntzBSHandler.renderPreview();});
    eval('AntzBSHandler.config.'+name+' = \''+value+'\';');
}


AntzBSHandler.saveElementProperty = function(elementId, name, value){
	var ajaxConfig = {
		ajaxCommand : 'save_element_property',
		element_id : elementId,
		name : name,
		value : value
	}
	$.get(this.config.ajaxUrl, ajaxConfig, function(){AntzBSHandler.renderPreview();});
	eval('AntzBSHandler.findElement(\''+elementId+'\').'+name+' = value;');
}

AntzBSHandler.savePropertyProperty = function(propertyInstanceId, name, value){
	var ajaxConfig = {
		ajaxCommand : 'save_property_property',
		property_instance_id : propertyInstanceId,
		name : name,
		value : value
	}
	$.get(this.config.ajaxUrl, ajaxConfig, function(){AntzBSHandler.renderPreview();});
	eval('AntzBSHandler.findProperty(\''+propertyInstanceId+'\').'+name+' = value;');
}

AntzBSHandler.saveWidgetProperty = function(widgetInstanceId, name, value){
	var ajaxConfig = {
		ajaxCommand : 'save_widget_property',
		widget_instance_id : widgetInstanceId,
		name : name,
		value : value
	}
	$.get(this.config.ajaxUrl, ajaxConfig, function(){AntzBSHandler.renderPreview();});
	eval('AntzBSHandler.findWidget(\''+widgetInstanceId+'\').'+name+' = value;');
}

AntzBSHandler.saveWindowPosition = function(element, nodeName){
	var left, top, ajaxConfig;
	left = $(element).css('left');
	top = $(element).css('top');

	this.saveHandlerProperty(nodeName+'NodePositionLeft', left);
	this.saveHandlerProperty(nodeName+'NodePositionTop', top);

	eval('this.config.'+nodeName+'NodePositionLeft = \''+left+'\';');
	eval('this.config.'+nodeName+'NodePositionTop = \''+top+'\';');
	

}


AntzBSHandler.init = function(handlerConfig){
    this.config = handlerConfig;
	this.config.ajaxUrl = this.config.ajaxUrl.replace('&amp;', '&');
	this.config.previewUrl = this.config.previewUrl.replace('&amp;', '&');
	this.config.cssUrl = this.config.cssUrl.replace('&amp;', '&');
    
	this.elementsNode = document.getElementById(this.config.elementsNode);
	this.controlNode = document.getElementById(this.config.controlNode);
	this.previewNode = document.getElementById(this.config.previewNode);
	this.outputNode = document.getElementById(this.config.outputNode);
	this.linkNode = document.getElementById(this.config.linkNode);
	
	//$(this.controlNode).resizable();
	
	$(this.previewNode).resizable();
	$(this.outputNode).resizable();

	var outputDraggableConfig = {
		handle : $('.jfx-toolbar-header', this.outputNode),
		stop : function(){
			AntzBSHandler.saveWindowPosition(AntzBSHandler.outputNode, 'output');
		}
	}
	var previewDraggableConfig = {
		handle : $('.jfx-toolbar-header', this.previewNode),
		stop : function(){
			AntzBSHandler.saveWindowPosition(AntzBSHandler.previewNode, 'preview');
		}
	}


	//$(this.controlNode).draggable(controlDraggableConfig);
	$(this.outputNode).draggable(outputDraggableConfig);
	$(this.previewNode).draggable(previewDraggableConfig);
	$(this.previewNode).click(function(){
		AntzBSHandler.focusWindow(this.id);
	});
	$(this.outputNode).click(function(){
		AntzBSHandler.focusWindow(this.id);
	});


	$(this.previewNode).css('display', 'none');

}


AntzBSHandler.focusWindow = function(id){
	this.previewNode.style.zIndex = 82;
	this.outputNode.style.zIndex = 82;

	document.getElementById(id).style.zIndex = 84;

	this.saveHandlerProperty('focusedWindow', id);

}


AntzBSHandler.displayControls = function(elementId){
	var element = this.findElement(elementId);
	if(typeof element === 'undefined') return;

	$('.widgets', this.controlNode).html('');

	for(var i=0; i<element.properties.length; i++){
		var property = element.properties[i];
		$('.widgets', this.controlNode).append(AntzBSWidget.toDom(property, element));
	}

	var title = '('+element.title+') '+AntzBSHandler.getSelector(element);

	$('#JFX_Module_Blockstyle_Elements li.selectedElement').removeClass('selectedElement');
	$('.jfx-element-'+elementId).addClass('selectedElement');

	$('#JFX_Module_Blockstyle_Editing_Element_Title').html(title);
	this.saveHandlerProperty('focusedElement', elementId);

}


AntzBSHandler.displayAjax = function(json){
	JFXParseAjaxContent(json);
	AntzBSHandler.renderPreview();
}

AntzBSHandler.display = function(){
	AntzBSHandler.displayControls(AntzBSHandler.config.elements[0].id);
	AntzBSHandler.renderPreview();
	
}

AntzBSHandler.saveWidget = function(widget){
	widget.ajaxCommand = 'save_widget';
	$.post(this.config.ajaxUrl, widget, AntzBSHandler.displayAjax);
	
}

AntzBSHandler.getAllElements = function(){
    var elements = Array();
    var i = 0;
    for(var ei=0; ei<this.config.elements.length; ei++){
		elements[i] = this.config.elements[ei];
		i++;
	}
    return elements;
}

AntzBSHandler.getAllProperties = function(){
    var properties = Array();
    var i = 0;
    for(var ei=0; ei<this.config.elements.length; ei++){
		for(var pi=0; pi<this.config.elements[ei].properties.length; pi++){
			properties[i] = this.config.elements[ei].properties[pi];
			i++;
		}
	}
    return properties;
}

AntzBSHandler.getAllWidgets = function(){
    var widgets = Array();
    var i = 0;
    for(var ei=0; ei<this.config.elements.length; ei++){
		for(var pi=0; pi<this.config.elements[ei].properties.length; pi++){
			for(var wi=0; wi<this.config.elements[ei].properties[pi].widgets.length; wi++){
				widgets[i] = this.config.elements[ei].properties[pi].widgets[wi];
                i++;
			}
		}
	}
    return widgets;
}

AntzBSHandler.save = function(silent){
	
	//newConfig.selectedElements = this.selectedElements;


	var allWidgets = this.getAllWidgets();
/*
	window.previewWindow.close();
	window.previewWindow = null;
*/

	for(var i=0; i<allWidgets.length; i++){
		var widget = this.findWidget(allWidgets[i].instanceId);
		for(var o=0; o<widget.privateProperties.length; o++){
			if(widget.privateProperties[o]=='privateProperties'){
				continue;
			}
			eval('delete AntzBSHandler.findWidget(\''+widget.instanceId+'\').'+widget.privateProperties[o]+';');
		}

		for(var o=0; o<widget.runtimeProperties.length; o++){
			if(widget.privateProperties[o]=='runtimeProperties'){
				continue;
			}
			eval('delete AntzBSHandler.findWidget(\''+widget.instanceId+'\').'+widget.runtimeProperties[o]+';');
		}
	}

	var allProperties = this.getAllProperties();
	for(var i=0; i<allProperties.length; i++){
		var property = this.findProperty(allProperties[i].instanceId);
		//alert('checking widget '+widget.instanceId+' with '+widget.privateProperties.length+' private properties');
		for(var o=0; o<property.privateProperties.length; o++){
			if(property.privateProperties[o]=='widgets' || property.privateProperties[o]=='privateProperties'){
				continue;
			}
			eval('delete AntzBSHandler.findProperty(\''+property.instanceId+'\').'+property.privateProperties[o]+';');
		}
	}

	var allElements = this.getAllElements();
	for(var i=0; i<allElements.length; i++){
		var element = this.findElement(allElements[i].id);
		if(!element.privateProperties) continue;
		for(var o=0; o<element.privateProperties.length; o++){
			if(element.privateProperties[o]=='properties' || element.privateProperties[o]=='privateProperties'){
				continue;
			}
			eval('delete AntzBSHandler.findElement(\''+element.id+'\').'+element.privateProperties[o]+';');
		}
	}


	var newConfig = JSON.parse(JSON.stringify(this.config));
	var newConfig = this.config;

	var saveConfig = {
		handler : JSON.stringify(newConfig),
		ajaxCommand : 'save_handler'
	}
	var returnFunction;

	if(!silent){
		returnFunction = function(json){AntzBSHandler.displayAjax(JSON.parse(json));};
	}else{
		returnFunction = function(){AntzBSHandler.renderPreview();};
	}

	$.post(this.config.ajaxUrl, saveConfig, returnFunction);
}

AntzBSHandler.toggleElement = function(elementId){
	var chk = $('input[name=enable_'+elementId+']').get(0);
	var element = this.findElement(elementId);
	element.enabled = chk.checked;
	this.save();
}

AntzBSHandler.getSelector = function(element){
	var selector = '.'+AntzBSHandler.config.classname+' '+element.tagname;
	if(element.id == 'block'){
		// it is the container element
		selector = '.'+AntzBSHandler.config.classname;
	}
	return selector;

}

AntzBSHandler.findElement = function(id){
	for(var i=0; i<this.config.elements.length; i++){
		if(this.config.elements[i].id == id){
			return this.config.elements[i];
		}
	}
}

AntzBSHandler.findProperty = function(instanceId){
	for(var ei=0; ei<this.config.elements.length; ei++){
		for(var pi=0; pi<this.config.elements[ei].properties.length; pi++){
			if(this.config.elements[ei].properties[pi].instanceId==instanceId){
				return this.config.elements[ei].properties[pi];
			}
		}
	}
}

AntzBSHandler.findWidget = function(instanceId){
	for(var ei=0; ei<this.config.elements.length; ei++){
		for(var pi=0; pi<this.config.elements[ei].properties.length; pi++){
			for(var wi=0; wi<this.config.elements[ei].properties[pi].widgets.length; wi++){
				if(this.config.elements[ei].properties[pi].widgets[wi].instanceId==instanceId){
					return this.config.elements[ei].properties[pi].widgets[wi];
				}
				if(this.config.elements[ei].properties[pi].widgets[wi].widgets){
					for(var wwi=0; wwi<this.config.elements[ei].properties[pi].widgets[wi].widgets.length; wwi++){
						if(this.config.elements[ei].properties[pi].widgets[wi].widgets[wwi].instanceId==instanceId){
							return this.config.elements[ei].properties[pi].widgets[wi].widgets[wwi];
						}
					}
				}
			}
		}
	}
	console.log('couldn\'t find '+instanceId);
}


AntzBSHandler.refreshCssOutput = function(){
	$('.pre', this.outputNode).html('');
	$.get(this.config.ajaxUrl, {ajaxCommand : 'getCssOutput'}, function(json){AntzBSHandler.displayCssOutput(json);});
}

AntzBSHandler.displayClassname = function(select){
	var classname = select.options[select.selectedIndex].value;
	var ajaxOptions = {
		ajaxCommand: 'change_classname',
		newClassname: classname
	}
	$.get(this.config.ajaxUrl, ajaxOptions, function(json){AntzBSHandler.displayAjax(JSON.parse(json));});
}

AntzBSHandler.displayCssOutput = function(text){
	$('.pre', this.outputNode).text(text);
	//this.outputNode.innerHTML = text;
}

AntzBSHandler.renderPreview = function(){
	if(window.previewWindow !== null){
		//alert('refreshing the window to '+window.previewWindow.location);
		window.previewWindow.location = window.previewWindow.location;
	}

}

if(window && !window.previewWindow){
	window.previewWindow = null;
}
$(window).unload(function(){
	if(window.previewWindow!==null){
		window.previewWindow.close();
		window.previewWindow = null;
	}
})
AntzBSHandler();

